#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <netdb.h>
#include <netinet/tcp.h>
#include <fcntl.h>

#define MAX_CMD_LEN  100 
#define POP3SERVPORT 110
#define MAXDATASIZE 4096
int main(int argc, char *argv[]){
	int sockfd;
	struct hostent *host;
	struct sockaddr_in serv_addr;
	char *POPMessage[]={
		"USER lhbf",
		"PASS liuhb.1@0169",
		"stat\n",
		NULL
	};
	int iLength;
	int iMsg=0;
	int iEnd=0;
	char buf[MAXDATASIZE];
	if((host=gethostbyname("pop.qq.com"))==NULL) {
		perror("gethostbyname error");
		exit(1);
	}
	if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1){
		perror("socket error");
		exit(1);
	}
	int flag = 1;
	setsockopt(sockfd, IPPROTO_TCP, TCP_NODELAY, (char *)&flag, sizeof(flag));
	serv_addr.sin_family=AF_INET;
	serv_addr.sin_port=htons(POP3SERVPORT);
	serv_addr.sin_addr = *((struct in_addr *)host->h_addr_list[0]);
	bzero(&(serv_addr.sin_zero),8);
	if (connect(sockfd, (struct sockaddr *)&serv_addr,sizeof(struct sockaddr))==-1){
		perror("connect error");
		exit(1);
	}
	else{
		printf("conecting......\n");
	}
	char *cmd;
	int closing = 0;
	fd_set fdr;
	struct timeval timeout = {1,0};
	do {
		int con;
		do{
			FD_ZERO(&fdr);
			FD_SET(sockfd, &fdr);
			select(sockfd+1, &fdr, NULL, NULL, &timeout);
			if(((iLength=read(sockfd, buf, MAXDATASIZE-1)) != -1)){
				buf[iLength] = '\0';
				printf("%s",buf);
				buf[0]='\0';
			}
		}while((iLength >= MAXDATASIZE-1) );

		cmd = malloc(MAX_CMD_LEN*sizeof(char));
		fflush(stdin);
		gets(cmd);

		if(strcmp(cmd, "close") == 0){
			closing = 1;
			close(sockfd);
		}
		if(!strlen(cmd)){
			continue;
		}

		strcat(cmd, "\r\n");

		if((write(sockfd, cmd, strlen(cmd))) == -1){
			printf("send error\n");
			exit(1);
		}
	} while (!closing);
	close(sockfd);
}
